package com.example.baseutils.net;

import android.app.Application;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.util.Log;

import com.example.baseutils.NetUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Author by lp,on 2021/12/21/021,15:32.
 */
public class NetState {
    private static final String TAG = "NetState";
    private boolean isInit = false;
    private List<NetListtenr> listtenrList = new CopyOnWriteArrayList<>();
    private NetChangeReceiver netChangeReceiver = new NetChangeReceiver(listtenrList);

    private static class Inner {
        private static NetState inner = new NetState();
    }

    private void NetState() {
    }

    public static NetState getInstance() {
        return Inner.inner;
    }

    //初始化，使用Application 避免内存泄露
    public void init(Application application) {
        if (isInit)
            return;
        isInit=true;
        NetUtil.register(application);
        //添加网络改变时的监听
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        application.registerReceiver(netChangeReceiver, filter);

    }

    public void addListtner(NetListtenr listtenr) {
        if (!listtenrList.contains(listtenr)) {
            Log.i(TAG, "addListtner: ");
            listtenrList.add(listtenr);
            listtenr.netState(netChangeReceiver.getNowState());
        }
    }

    public boolean getNetState(){
        return netChangeReceiver.getNowState();
    }

    public void removeListtner(NetListtenr listtenr) {
        Log.i(TAG, "addListtner: ");
        listtenrList.remove(listtenr);

    }
}

